/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.hazelcast;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class HazelcastUtil {

    private static final Logger logger = Logger.getLogger(HazelcastUtil.class.getName());
    private static HazelcastInstance instance;
    private static String mapName = "myMap";
    private static String queueName = "myQueue";

    static {
        Config cfg = new Config();
        instance = Hazelcast.newHazelcastInstance(cfg);
    }

    /**
     * 获取Hazelcast实例(单例)
     *
     * @return
     */
    public static HazelcastInstance getHazelcastInstance() {
        return instance;
    }

    /**
     * 从分布式Map中获取
     *
     * @param key
     * @return
     */
    public static String getFromMap(String key) {
        Map<String, String> myMap = instance.getMap(mapName);
        String value = myMap.get(key);
        return value;
    }

    /**
     * 存储到分布式Map
     *
     * @param key
     * @param value
     */
    public static void putIntoMap(String key, String value) {
        Map<String, String> myMap = instance.getMap(mapName);
        myMap.put(key, value);
    }

    /**
     * 从分布式队列头获取一个元素，获取后元素删除
     *
     * @param key
     * @return
     */
    public static String getFromQueue(String key) {
        Queue<String> queueCustomers = instance.getQueue(queueName);
        String value = queueCustomers.poll();
        return value;
    }

    /**
     * 从分布式队列头获取一个元素，获取后元素不删除
     *
     * @param key
     * @return
     */
    public static String getFromQueueWithoutRemove(String key) {
        Queue<String> queueCustomers = instance.getQueue(queueName);
        String value = queueCustomers.peek();
        return value;
    }

    /**
     * 在分布式队列尾部加入一个元素
     *
     * @param value
     */
    public static void putIntoQueue(String value) {
        Queue<String> queueCustomers = instance.getQueue(queueName);
        queueCustomers.offer(value);
    }

    /**
     * 获取分布式Map实例
     *
     * @return
     */
    public static Map<String, String> getMapInstance() {
        return instance.getMap(mapName);
    }

    /**
     * 获取分布式Queue实例
     *
     * @return
     */
    public static Queue<String> getQueueInstance() {
        return instance.getQueue(queueName);
    }
}
